<template>
  <div>
    <el-upload
      action="#"
      list-type="picture-card"
      :on-preview="handlePictureCardPreview"
      :file-list="filelist"
      :on-remove="onremove"
      :before-upload="beforeupload"
      :on-change="onChange"
      :http-request="upload"
      :class="{disable:filelist.length>0}"
    >
      <i class="el-icon-plus" />
    </el-upload>
    <el-progress
      v-if="percent"
      :percentage="progressBar"
      style="width:148px"
      :show-text="false"
    />
    <el-dialog
      title="预览"
      :visible="showbig"
      :modal="true"
      :close-on-click-modal="true"
    >
      <el-row type="flex" justify="center">

        <img :src="Preurl" alt="">
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5'
const cos = new COS({
  SecretId: 'AKIDvgCRP8bmgKhncASUFjxuaz80bvzrSmpc',
  SecretKey: 'Yqqb5JH8j38vSihOpzsTosfCSSBdojMj'
})
export default {

  data() {
    return {
      progressBar: 0,
      Preurl: '',
      showbig: false,
      percent: false,
      filelist: [

      ]
    }
  },

  mounted() {

  },

  methods: {
    handlePictureCardPreview(file) {
      this.Preurl = file.url
      this.showbig = true
    },
    onChange(file, newfile) {
      this.filelist = [...newfile]
    },
    onremove(file, newfile) {
      this.filelist = [...newfile]
    },
    beforeupload(file) {
      const types = ['image/jpeg', 'image/png', 'image/gif']
      if (!types.includes(file.type)) {
        this.$message('图片格式错误')
        return false
      }
      const num = 500 * 1024
      if (file.size > num) {
        this.$message('图片过大')
        return false
      }
    },
    upload(params) {
      console.log(params)
      this.percent = true
      cos.putObject({
        // 储存桶名
        Bucket: 'matou-1306480900',
        // 储存桶区域
        Region: 'ap-guangzhou',
        // 要储存的文件名
        Key: params.file.name,
        // 储存类型,标准,固定不变
        StorageClass: 'STANDARD',
        // 文件对象本身
        Body: params.file,
        // 进度发生变化时回调
        onProgress: (progressData) => {
          console.log(JSON.stringify(progressData))
          this.progressBar = progressData.percent * 100
        }
      }, (err, data) => {
        // 上传完毕的回调不管成功失败都会到这
        // console.log(err || data)
        if (!err) {
          this.filelist[0].url = 'http://' + data.Location
          this.filelist[0].status = 'success'
        }
        setTimeout(() => {
          this.percent = false
        }, 800)
      })
    }
  }
}
</script>

<style lang="scss" scoped>
img{
  object-fit: cover;
}
.disable {
  // /deep/ .el-upload--picture-card {
  ::v-deep .el-upload--picture-card {
    display: none;
  }
}

</style>
